package cn.liutao.auth.api;

import cn.hutool.core.bean.BeanUtil;
import cn.liutao.auth.entity.dto.UserDto;
import cn.liutao.auth.entity.param.LoginParam;
import cn.liutao.auth.entity.po.User;
import cn.liutao.auth.service.AuthService;
import cn.liutao.common.enums.CommonEnum;
import cn.liutao.common.utils.JwtUtils;
import cn.liutao.common.utils.RedisUtils;
import cn.liutao.common.utils.ServletUtils;
import cn.liutao.common.utils.ValidUtil;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.groups.Default;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author liutao
 * @Description 实现登录功能
 * @date 2023/10/30 19:33
 * @Version 1.0
 */
@WebServlet("/auth/login")
@Slf4j
public class LoginServlet extends HttpServlet {

    private AuthService authService;
    /**
     * 初始化
     * @param config
     * @throws ServletException
     */
    @Override
    public void init(ServletConfig config) throws ServletException {
        authService = AuthService.getInstance();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp){
        LoginParam loginParam = JSONObject.parseObject(cn.hutool.extra.servlet.ServletUtil.getBody(req), LoginParam.class);
        //表单校验
        ValidUtil.validated(loginParam, Default.class);
        //实现验证码校验
        authService.verify(loginParam);
        //登录
        User user = authService.login(loginParam);
        //登录成功，返回token
        JwtUtils jwtUtils = new JwtUtils();
        //将用户信息保存到token中
        UserDto userDto = new UserDto();
        BeanUtil.copyProperties(user,userDto,"password","isAdmin");
        userDto.setIsAdmin(loginParam.getIsAdmin());
        String userinfo = JSONObject.toJSONString(userDto);
        String token = jwtUtils.generateToken(userinfo);
        String key;
        //将token 存入redis,用于实现单点登录
        if (loginParam.getIsAdmin().compareTo(CommonEnum.SYS_IS_ADMIN.getIntValue())==0){
            //管理员
             key= CommonEnum.LOGIN_KEY.getValue()+CommonEnum.SYS_IS_ADMIN.getDesc()+ user.getUsername();
        }else{
            //非管理员
            key= CommonEnum.LOGIN_KEY.getValue()+CommonEnum.SYS_NOT_ADMIN.getDesc()+ user.getUsername();
        }
        RedisUtils.set(key,token);
        Map map = new LinkedHashMap();
        map.put("token","Bearer "+token);
        map.put("isAdmin",user.getIsAdmin());
        ServletUtils.ok(resp,map,"登陆成功");
    }
}
